package com.linzp.bishe.exception;

import com.linzp.bishe.common.Result;
import com.linzp.bishe.controller.exception.ServiceException;
import com.linzp.bishe.utils.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常处理器
 * @Author LinZePeng
 * @Date 2021/12/12 1:25
 * @Version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	/**
	 * 权限校验异常
	 */
	@ExceptionHandler(AccessDeniedException.class)
	public Result handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		return Result.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
	}

	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
	                                                      HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		return Result.error(e.getMessage());
	}

	/**
	 * 业务异常
	 */
	@ExceptionHandler(ServiceException.class)
	public Result handleServiceException(ServiceException e, HttpServletRequest request)
	{
		String code = e.getCode();
		return code != null ? Result.error(code, e.getMessage()) : Result.error(HttpStatus.BAD_REQUEST,e.getMessage());
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(RuntimeException.class)
	public Result handleRuntimeException(RuntimeException e, HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		return Result.error(e.getMessage());
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public Result handleException(Exception e, HttpServletRequest request)
	{
		String requestURI = request.getRequestURI();
		return Result.error(e.getMessage());
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(BindException.class)
	public Result handleBindException(BindException e)
	{
		String message = e.getAllErrors().get(0).getDefaultMessage();
		return Result.error(message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
	{
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return Result.error(message);
	}
}
